import { Reducer } from 'redux';
import { Effect } from 'dva';
import { PersonalRadioItem } from '@/domains/radio';
import { getInternetList } from './service';

export interface StateType {
  radioList: PersonalRadioItem[];
  selected: PersonalRadioItem | null;
  tabKey: string;
}

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    fetchRadioList: Effect;
  };
  reducers: {
    saveData: Reducer;
    changeSelected: Reducer;
  };
}

const model: ModelType = {
  namespace: 'internetRadio',

  state: {
    radioList: [],
    selected: null,
    tabKey: '',
  },

  effects: {
    *fetchRadioList({ payload, callback }, { call, put }) {
      const radioList: PersonalRadioItem[] = yield call(getInternetList);
      yield put({
        type: 'saveData',
        payload: { radioList, selected: radioList[0], tabKey: payload },
      });
      if (callback) callback();
    },
  },

  reducers: {
    saveData(state, { payload }) {
      return { ...state, ...payload };
    },
    changeSelected(state, { payload }) {
      const { selected, radioList } = state;
      if (radioList.length) {
        if (selected) {
          const index = radioList.findIndex((item: PersonalRadioItem) => item.id === selected.id);
          if (payload === 'next') {
            if (index === radioList.length - 1) {
              return { ...state, selected: radioList[0] };
            }
            return { ...state, selected: radioList[index + 1] };
          }
          if (index === 0) {
            return { ...state, selected: radioList[radioList.length - 1] };
          }
          return { ...state, selected: radioList[index - 1] };
        }
        return { ...state, selected: radioList[0] };
      }
      return state;
    },
  },
};

export default model;
